﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
namespace Zeus.Mvc.Middlewares
{
    using Loggers;
    public class HttpContextLoggerMiddleware
    {
        readonly RequestDelegate _next;

        public HttpContextLoggerMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            using (var httpContextLogger = context.RequestServices.GetRequiredService<IHttpContextLogger>())
            {
                try
                {
                    await httpContextLogger.RequestLog(context);
                    await _next(context);
                    await httpContextLogger.ResponseLog(context);
                }
                catch (Exception ex)
                {
                    await httpContextLogger.ExceptionLog(context, ex);
                }
            }
        }
    }
}
